<?php
require_once 'config.php';

session_start();

// 用户登录验证
function login($username, $password)
{
    $conn = dbConnect();
    $stmt = $conn->prepare('SELECT id, password, username,role FROM users WHERE username = ?');
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] =  $user['username'];
            $_SESSION['role'] = $user['role'];
            return true;
        }
    }
    return false;
}

// 检查用户是否登录
function isLoggedIn()
{
    return isset($_SESSION['user_id']);
}

// 注销功能
function logout()
{
    session_unset();
    session_destroy();
}

// 访问控制中间件
function requireLogin()
{
    if (!isLoggedIn()) {
        header('Location: login.php');
        exit;
    }
}

function requireAdmin()
{
    requireLogin();
    if ($_SESSION['role'] !== 'admin') {
        header('HTTP/1.0 403 Forbidden');
        exit('无权限访问');
    }
}
